package com.fivefu.core.gb28181.service.impl;

import com.fivefu.core.gb28181.pojo.DeviceBean;
import com.fivefu.core.gb28181.service.CatalogDeviceService;
import com.fivefu.core.gb28181.utils.PTZUtils;
import com.fivefu.core.gb28181.utils.SipMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sip.*;
import java.text.ParseException;

@Service
public class CatalogDeviceServiceImpl implements CatalogDeviceService {

    @Autowired
    private SipMessageUtils sipMessageUtils;

    DeviceBean bean = new DeviceBean("34020000001180000001","192.168.0.144",5060,"udp");


    /**
     * 查询目录和设备结构
     * @param deviceID
     * @param CmdType (Catalog:目录,DeviceInfo:设备,DeviceStatus:设备状态)
     * @throws InvalidArgumentException
     * @throws ParseException
     * @throws SipException
     */
    @Override
    public void queryCatalogDevice(String deviceID, String CmdType) throws InvalidArgumentException, ParseException, SipException {
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\"?>\n");
        sb.append("<Query>\n");
        sb.append("<CmdType>" + CmdType + "</CmdType>\n");
        sb.append("<SN>" + (int)((Math.random()*9+1)*100000) + "</SN>\n");
        sb.append("<DeviceID>" + deviceID + "</DeviceID>\n");
        sb.append("</Query>\n");


        String viaTag = "gb28181_viaTag";
        String fromTag = "gb28181_fromTag";
        String toTag = null;

        ClientTransaction transaction = sipMessageUtils.sendMessage(bean,viaTag, fromTag, toTag, sb.toString());
        transaction.sendRequest();
    }

    /**
     * 云台操作
     * @param deviceID 设备编号
     * @param ptzType 云台操作
     * @param active 状态(0:停止,1:启动)
     * @param speed 速度
     * @throws InvalidArgumentException
     * @throws ParseException
     * @throws SipException
     */
    @Override
    public void ptzDevice(String deviceID, String ptzType, Integer active, Integer speed) throws InvalidArgumentException, ParseException, SipException {
        String ptzCmd = PTZUtils.ptzControlCmd(ptzType,active,speed);
        String xml = "<?xml version=\"1.0\"?>\n" +
                "<Control>\n" +
                "<CmdType>DeviceControl</CmdType>\n" +
                "<SN>" + (int)((Math.random()*9+1)*100000) + "</SN>\n" +
                "<DeviceID>" + deviceID + "</DeviceID>\n" +
                "<PTZCmd>" + ptzCmd + "</PTZCmd>\n" +
                "<Info>\n" +
                "<ControlPriority>3</ControlPriority>\n" +
                "</Info>\n" +
                "</Control>\n";
        String viaTag = "gb28181_viaTag";
        String fromTag = "gb28181_fromTag";
        String toTag = null;

        ClientTransaction transaction = sipMessageUtils.sendMessage(bean,viaTag, fromTag, toTag, xml);
        transaction.sendRequest();
    }


}
